package com.summer.mall.service.impl;

import com.alibaba.fastjson.support.hsf.HSFJSONUtils;
import com.google.common.collect.Lists;
import com.summer.mall.common.ResponseFileService;
import com.summer.mall.common.ResponseService;
import com.summer.mall.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;

@Service("fileService")
public class FileServiceImpl implements FileService {

    private static final String url = "localhost:8080/uploads/";
    private static final String uuid = UUID.randomUUID().toString();

    @Override
    public String upload(MultipartFile file, String path) {
        String fileName = file.getOriginalFilename();
        //获取扩展名jpg
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        //为了避免相同文件名出现被覆盖的情况出现,
        String uploadFileName = uuid +"."+ fileExtensionName;
        //设置文件上传路径

        ResponseFileService.createFileByCodeWaitMessage("开始上传文件,上传的文件按名:{},上传的路径:{},新文件名:{}",fileName,path,fileExtensionName);
        File filedir = new File(path);
        if (!filedir.exists()){
            filedir.setWritable(true);
            filedir.mkdirs();
        }
        File torgetFile = new File(path,uploadFileName);

        try {
            file.transferTo(torgetFile);

            //上传完后删除upload下面的文件
            torgetFile.delete();

        } catch (IOException e) {
         ResponseService.createByErrorMessage("上传文件异常");
            return null;
        }
        return torgetFile.getName();
    }



}
